package com.dean.netty.server;

import com.dean.netty.entity.DeanNettySendMsg;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class DeanNettyServerHandler extends ChannelInboundHandlerAdapter {
    private final Logger logger = LoggerFactory.getLogger(DeanNettyServerHandler.class);

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if(msg instanceof DeanNettySendMsg){
            DeanNettySendMsg sendMsg = (DeanNettySendMsg) msg;

        }else{
            logger.info("错误的消息格式");
        }
        logger.info("服务端接受到一条来自{}的消息,消息内容是:{}",ctx.channel().remoteAddress(),msg);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        String ip = ctx.channel().remoteAddress().toString();
        logger.info("ip:{}的用户已上线",ip);
        DeanNettyServerInit.getUserGroups().put(ip,ctx);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        logger.info("ip:{}的用户已下线",ctx.channel().remoteAddress());
    }

    // 服务器转发消息给客户端 实现客户端->客户端
    public void sendMsg(String toIP,String msg){
        ChannelHandlerContext ctx = DeanNettyServerInit.getUserGroups().get(toIP);
        ctx.channel().writeAndFlush(msg);
    }

    //    protected void channelRead0(ChannelHandlerContext channelHandlerContext, String receiveMsg) throws Exception {
//        // 通过ctx获取客户端的IP和端口号，并打印出客户端发来的消息
//        logger.info("服务端接受到一条来自{}的消息,消息内容是:{}",channelHandlerContext.channel().remoteAddress(),receiveMsg);
//
//        channelHandlerContext.channel().writeAndFlush("已收到消息,请");
//    }
}
